<template>
  <div class="nursing-home-card">
    <!-- 头部标题 -->
    <el-row justify="space-between" align="middle" class="header">
      <el-col :span="24">
        <h2 class="title">{{ state.ruleForm.name }}</h2>
      </el-col>
    </el-row>

    <!-- 图片和活动介绍 -->
    <el-row :gutter="20">
      <!-- 图片 -->
      <el-col :span="12">
        <img :src="state.ruleForm.cover" alt="图片" class="home-image">
      </el-col>
      <!-- 活动介绍 -->
      <el-col :span="12">
        <br>
        <br>
        <div class="activity-info">
          <p><strong>日期：</strong>{{ state.ruleForm.startDate }} ~ {{ state.ruleForm.endDate }}</p>
          <p><strong>地址：</strong>{{ state.ruleForm.address }}</p>
          <br>
          <br>
        </div>
        <div class="activity-register">
          <el-button
              type="primary"
              :icon="Edit"
              @click="handleregister"
              :disabled="!canRegister"
          >
            {{ statusText }}
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 项目简介（活动详情） -->
    <div class="project-introduction">
      <h1>活动详情</h1>
      <div v-html="state.ruleForm.content"></div>
    </div>
    <div class="comment-section">
      <h2>评论区{{ state.comments.length }}条</h2>

      <!-- 评论列表 -->
      <ul class="comment-list">
        <li v-for="comment in state.comments" :key="comment.id" class="comment-item">
          <div class="comment-header">
            <el-avatar :size="30" :src="comment.avatar"/>
            <div class="user-info">
              <span class="username">{{ comment.name }}</span>
              <span class="time">{{ formatTime(comment.createTime) }}</span>
            </div>
          </div>
          <p class="comment-content">{{ comment.content }}</p>

          <div class="reply-section">
            <el-button
                size="small"
                @click="toggleReply(comment)"
                class="reply-btn"
            >
              {{ comment.showReply ? '取消回复' : '回复' }}
            </el-button>

            <!-- 回复表单 -->
            <div v-if="comment.showReply" class="reply-form">
              <el-input
                  v-model="state.replyContent"
                  placeholder="写下你的回复..."
                  type="textarea"
                  :rows="2"
              />
              <el-button
                  type="primary"
                  size="small"
                  @click="submitReply(comment)"
                  class="submit-btn"
              >
                提交回复
              </el-button>
            </div>

            <!-- 回复列表 -->
            <ul
                v-if="comment.childCommentList?.length"
                class="reply-list"
            >
              <li
                  v-for="reply in comment.childCommentList"
                  :key="reply.id"
                  class="reply-item"
              >
                <div class="comment-header">
                  <el-avatar :size="30" :src="reply.avatar"/>
                  <div class="user-info">
                    <span class="username">{{ reply.name }}</span>
                    <span class="time">{{ formatTime(reply.createTime) }}</span>
                  </div>
                </div>
                <p class="comment-content">{{ reply.content }}</p>
              </li>
            </ul>
          </div>
        </li>
      </ul>

      <!-- 新评论表单 -->
      <div class="new-comment">
        <h3>发表评论</h3>
        <el-input
            v-model="state.newComment"
            placeholder="写下你的评论..."
            type="textarea"
            :rows="4"
        />
        <el-button
            type="primary"
            @click="submitComment"
            class="submit-btn"
        >
          提交评论
        </el-button>
      </div>
    </div>
  </div>

  <!-- 评论区 -->
  <el-dialog
      v-model="dialogVisible"
      title="确认报名"
      width="30%"
  >
    <div class="review-form">
      <p>您确定要报名该活动吗？</p>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="ActivityRegister">确定</el-button>
    </template>
  </el-dialog>

  <div class="footer">
    <div>社区养老服务整合平台</div>

  </div>
</template>

<script setup>

import {ElMessage} from 'element-plus';
import {ref, onMounted, reactive, computed} from 'vue';
import {useRoute} from 'vue-router';
import {clientgetActivityById} from '../../service/activityApi.js';
import {ClientlistcommentInfo, ClientAddComment, ClientReplyComment} from '../../service/commentinfoApi.js'
import {AddActivityRegistration} from '../../service/activityRegistrationApi.js'

const route = useRoute();
const dialogVisible = ref(false);
onMounted(() => {
  getActivityDetail();
  getCommennts()
});


const handleregister = () => {
  dialogVisible.value = true
}
const state = reactive({
  ruleForm: {
    id: '',
    name: '',
    summary: '',
    cover: '',
    content: '',
    address: '',
    startDate: '',
    endDate: '',
  },
  comments: [],
  newComment: '',
  replyContent: '',
  showReply: false
});

const getActivityDetail = async () => {
  // 查询公益活动单个数据
  const result = await clientgetActivityById(route.params.id);
  // 数据回显
  state.ruleForm = {
    name: result.data.name,
    summary: result.data.summary,
    cover: result.data.cover,
    content: result.data.content,
    address: result.data.address,
    startDate: result.data.startDate.split(' ')[0],
    endDate: result.data.endDate.split(' ')[0],
  };
};

const getCommennts = async () => {
  const result = await ClientlistcommentInfo(route.params.id);
  state.comments = result.data
};


// 格式化时间显示
const formatTime = (timeStr) => {
  return new Date(timeStr).toLocaleString();
};

// 提交新评论
const submitComment = async () => {
  if (!state.newComment.trim()) {
    ElMessage.warning('请输入评论内容');
    return;
  }
  // 构建请求参数
  const params = {
    content: state.newComment,
    id: "",
    module: "activity",
    relatedId: '',
    rootId: route.params.id
  };
  const result = await ClientAddComment(params);
  state.newComment = '';
  ElMessage.success(result.msg);
  await getCommennts()
};

// 提交回复
const submitReply = async (comment) => {
  if (!state.replyContent.trim()) {
    ElMessage.warning('请输入回复内容');
    return;
  }
  const params = {
    content: state.replyContent,
    module: "activity",
    parentId: comment.id,
    relatedId: "",
    rootId: route.params.id
  };
  comment.showReply = false;
  const result = await ClientReplyComment(params);
  state.replyContent = '';
  ElMessage.success(result.msg);
  // 刷新页面
  await getCommennts()
};

// 切换回复框显示
const toggleReply = (comment) => {
  comment.showReply = !comment.showReply;
};


//活动报名
const activityStatus = computed(() => {
  const now = new Date()
  const start = new Date(state.ruleForm.startDate)
  const end = new Date(state.ruleForm.endDate)

  // 精确时间处理
  start.setHours(0, 0, 0, 0)
  end.setHours(23, 59, 59, 999)

  if (now < start) return 'not-started'
  if (now > end) return 'expired'
  return 'active'
})

const canRegister = computed(() => {
  return activityStatus.value === 'not-started' // 仅未开始时可点击
})

const statusText = computed(() => {
  return {
    'not-started': '立即预报名',
    'active': '活动进行中（不可报名）',
    'expired': '活动已结束'
  }[activityStatus.value]
})

const ActivityRegister = async () => {
  const res = await AddActivityRegistration(route.params.id)
  dialogVisible.value = false
  ElMessage.success(res.msg);
}
</script>

<style scoped>

.nursing-home-card {
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fff;
  max-width: 1000px;
  margin: 0 auto;
  background-color: #f5f5f5;
}

.header {
  margin-bottom: 16px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.home-image {
  width: 100%;
  height: auto;
  border-radius: 8px;
}

.activity-info {
  margin-bottom: 16px;
}

.activity-info p {
  margin: 4px 0;
  color: #666;
}

.status {
  color: #f56c6c;
  font-weight: bold;
}

.activity-register {
  margin-bottom: 16px;
}

.activity-details h3 {
  font-size: 20px;
  color: #333;
  margin-bottom: 8px;
}

.activity-details p {
  color: #666;
  line-height: 1.6;
}

.project-introduction {
  margin-bottom: 16px;
  text-align: center; /* 内容居中 */
}

.project-introduction h1 {
  font-size: 24px;
  color: #333;
  margin-bottom: 16px;
}

.project-introduction p {
  color: #666;
  line-height: 1.6;
  max-width: 600px; /* 限制内容宽度 */
  margin: 0 auto; /* 内容居中 */
}

.comment-section {
  margin-top: 40px;
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

.comment-list {
  list-style: none;
  padding: 0;
}

.comment-item {
  padding: 20px;
  margin-bottom: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  margin-left: 10px;
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 500;
  color: #333;
}

.time {
  font-size: 12px;
  color: #999;
}

.comment-content {
  margin: 10px 0;
  color: #333;
  line-height: 1.6;
}

.reply-section {
  margin-left: 30px;
  padding-left: 20px;
  border-left: 2px solid #eee;
}

.reply-form {
  margin: 15px 0;
}

.submit-btn {
  margin-top: 10px;
}

.new-comment {
  margin-top: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.reply-list {
  list-style: none;
  padding-left: 20px;
  margin-top: 15px;
}

.reply-item {
  padding: 10px;
  margin: 10px 0;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 6px;
}

.new-comment {
  background-color: #ffffff;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.footer {
  font-size: 14px;
  height: 100px; /* 根据需要调整高度 */
  border-top: 1px solid #e9e9e9;
  display: flex;
  flex-direction: row; /* 水平排列 */
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.beian-footer {
  bottom: 0;
  text-align: center;

a {
  color: #1D1D26;
  font-size: 14px;
  text-decoration-line: underline;

&
:hover {
  color: #409EFF;
}

}
}

</style>